package com.hps.webservice.config;

import org.apache.cxf.binding.soap.SoapHeader;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.springframework.util.StringUtils;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;

import javax.xml.soap.SOAPException;
import java.util.List;

/**
 * @author hepengshuai
 * @date 2018/12/7 21:27
 */
public class AuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

    private static final String USERNAME = "root";
    private static final String PASSWORD ="123456";

    public AuthInterceptor() {
        super(Phase.PRE_PROTOCOL);
    }

    @Override
    public void handleMessage(SoapMessage soapMessage) throws Fault {
        List<Header> headers = null;
        String username = null;
        String password = null;
        headers = soapMessage.getHeaders();
        if (headers == null) {
            throw new Fault(new IllegalArgumentException("找不到Header, 无法验证用户信息"));
        }

        // 获取用户名，密码
        for (Header header : headers) {
            SoapHeader soapHeader = (SoapHeader) header;
            Element e = (Element) soapHeader.getObject();
            NodeList usernameNode = e.getElementsByTagName("username");
            NodeList passwordNode = e.getElementsByTagName("password");
            username = usernameNode.item(0).getTextContent();
            password = passwordNode.item(0).getTextContent();
            if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
                throw new Fault(new IllegalArgumentException("用户信息为空"));
            }
        }

        if (!(USERNAME.equals(username) && PASSWORD.equals(password))) {
            SOAPException soapException = new SOAPException("认证失败");
            throw new Fault(soapException);
        }
    }
}
